var pomelo = window.pomelo;
// const config = require('../../../config');
const config = {
  dev: {
    serverSockIp: '127.0.0.1',
    serverSockPort: 3014,
  }
};

pomelo.on('onAdd', function (ret) {
  if (ret.code != 200) {
    return;
  }

  client.studentList.push(ret.data);
});

pomelo.on('onLeave', function (ret) {
  if (ret.code != 200) {
    return;
  }

  for (var i = 0; i < client.studentList.length; i++) {
    if (client.studentList[i].userno == ret.data.user) {
      client.studentList.splice(i, 1);
      break;
    }
  }
});

pomelo.on('onChat', function (ret) {
  if (ret.code != 200 || ret.data.from == client.userno) {
    return;
  }

  switch (ret.data.msgType) {
    case 1: {
      client.postsList.push(ret.data.msgContent);
    }
      break;
    case 2: {
      client.boardSeries.push(ret.data.msgContent);
    }
      break;
    default:
      break;
  }

});

pomelo.on('disconnect', function (reason) {
  console.log('reason', reason)
});

export const client = {
  userno: 0,
  classroomno: 0,
  studentList: [],
  postsList: [],
  boardSeries: [],
  enter: function (userno, classroomno) {
    var self = this;
    this.userno = userno;
    this.classroomno = classroomno;

    pomelo.init({
      host: config.dev.serverSockIp,
      port: config.dev.serverSockPort
    }, function () {
      pomelo.request('gate.gateHandler.queryEntry', {
        uid: userno + ''
      }, function (ret) {
        pomelo.disconnect();

        if (ret.code != 200) {
          toastr.error('连接服务器失败，请刷新页面重新连接', '请求异常');
          return;
        }

        pomelo.init({
          host: ret.data.host,
          port: ret.data.port,
          log: true
        }, function () {
          pomelo.request("connector.entryHandler.enter", {
            username: userno,
            rid: classroomno
          }, function (ret) {
            if (ret.code != 200) {
              toastr.error('连接服务器失败，请刷新页面重新连接', '请求异常');
              return;
            }
            self.studentList = ret.data.users;
          });
        });
      });
    });
  },
  leave: function () {
    pomelo.disconnect();
    this.userno = 0;
    this.classroomno = 0;
    this.studentList = [];
    this.postsList = [];
  },
  send: function (target, msgType, msgContent) {
    var self = this;
    pomelo.request("chat.chatHandler.send", {
      target: target,
      msgType: msgType,
      msgContent: msgContent
    }, function (ret) {
      console.log(ret)
    });
  }
};
